import { BaseModel } from '@/uni_modules/stars-UniTS-SQLite-ORM/components/stars-UniTS-SQLite-ORM/dbOrm/model/BaseModel';
import { PageModel } from '@/uni_modules/stars-UniTS-SQLite-ORM/components/stars-UniTS-SQLite-ORM/dbOrm/model/PageModel';
import { ISqliteService } from '@/uni_modules/stars-UniTS-SQLite-ORM/components/stars-UniTS-SQLite-ORM/dbOrm/service/ISqliteService';
import { SqliteServiceImpl } from '@/uni_modules/stars-UniTS-SQLite-ORM/components/stars-UniTS-SQLite-ORM/dbOrm/service/impl/SqliteServiceImpl';
import { User } from '../model/User';
import { Transactional } from '@/uni_modules/stars-UniTS-SQLite-ORM/components/stars-UniTS-SQLite-ORM/dbOrm/TransactionManager/Transactional';

export class UserServiceImpl {

	// 创建实现类的实例
	private sqliteService : ISqliteService<BaseModel>;

	constructor() {
		this.sqliteService = new SqliteServiceImpl<BaseModel>();
	}

	// 事务测试
	@Transactional
	transactionalTest(user : User) : void {
		console.log("处理业务逻辑开始");
		this.sqliteService.insert(user);
		let users = new User();
		users.id = 1;
		users.name = '这是更改后的名字';
		this.sqliteService.update(users);
		this.sqliteService.deleteById(2, User);
		// 制造一个异常
		this.sqliteService.update(null);
		throw new Error("制造一个异常");
		console.log("处理业务逻辑结束");
	}

	// 插入用户
	async insertUser(user : User) : Promise<void> {
		return await this.sqliteService.insert(user);
	}

	// 根据 ID 获取用户
	async getUserById(id : number) : Promise<User> {
		return await this.sqliteService.selectById(id, User);
	}

	// 获取所有用户
	async getUsers() : Promise<User[]> {
		return await this.sqliteService.selectAll(User);
	}

	// 根据条件获取用户
	async getUsersByCondition(condition : string) : Promise<User[]> {
		return await this.sqliteService.selectByCondition(condition, User);
	}

	/**
	 * 分页查询用户
	 */
	async getUsersByPage(page : number, size : number, condition ?: string, orderBy ?: string) : Promise<PageModel> {
		return await this.sqliteService.selectByPage(page, size, condition, orderBy, User);
	}

	// 更新用户
	async updateUser(user : User) : Promise<void> {
		return await this.sqliteService.update(user);
	}

	// 根据 ID 删除用户
	async deleteUserById(id : number) : Promise<void> {
		return await this.sqliteService.deleteById(id, User);
	}

	// 根据条件删除用户
	async deleteUserByCondition(condition : string) : Promise<void> {
		return await this.sqliteService.deleteByCondition(condition, User);
	}
}